package tianrun.ziguan.api.calculate.config.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import tianrun.ziguan.api.calculate.config.cache.TableCascade;
import tianrun.ziguan.api.calculate.config.cache.TableCascadeCache;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.list.ListBody;
import tianrun.ziguan.api.calculate.config.service.common.CommonService;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class DeleteListener {

    private final TGeTableConfigService tableConfigService;
    private final CommonService commonService;

    public DeleteListener(TGeTableConfigService tableConfigService, CommonService commonService) {
        this.tableConfigService = tableConfigService;
        this.commonService = commonService;
    }

    @EventListener
    public void cascadeDelete(DeleteBody event) {
        String parentTable = event.getTableName();
        List<TableCascade> list = TableCascadeCache.get(parentTable);
        if (list == null) {
            return;
        }
        list.forEach(i -> {
            String tableName = i.getRelationTable();
            String primaryKey = tableConfigService.primaryKey(tableName);
            if (StringUtils.isBlank(primaryKey)) {
                return;
            }
            ListBody listBody = getListBody(event, i, primaryKey);
            List<Map<String, Object>> _list = commonService.list(listBody, false);
            if (_list.isEmpty()) {
                return;
            }
            Set<Long> ids = _list.stream().map(item -> MapUtil.getLong(item, primaryKey)).collect(Collectors.toSet());
            DeleteBody deleteBody = new DeleteBody(tableName, ids);
            commonService.delete(deleteBody);
        });
    }

    private static ListBody getListBody(DeleteBody event, TableCascade i, String key) {
        ListBody listBody = new ListBody();
        listBody.setTableName(i.getRelationTable());
        listBody.setColumns(Collections.singletonList(key));
        listBody.setFilterFields(i.toFilterFields(event.getIds()));
        return listBody;
    }

}

